//
//  DetailViewController.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 12/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift
import MediaPlayer


struct MyStruct
{
    init( _apis : APIStruct)
    {
        
        num1 = _apis.num1
        testNumber = _apis.testNumber
    }
    
    var     num1 : UInt16
    var     testNumber : UnsafeMutablePointer<Int8>

}

//设置回调函数
func swiftCallBackVoid( p: UnsafeMutablePointer<APIStruct> )
{

    //let _locMS:MyStruct = (UnsafeMutablePointer<MyStruct>(p)).memory;
    
    print("-----Get the data------")

   // print(p[0].testNumber)
   // print(p[0].toUserID)
    


    if p[0].chat_mode == 3 {
        //私人聊天，则要通知私人模式下监控
        let str = String(CString: UnsafePointer<CChar>(p[0].testNumber), encoding: NSUTF8StringEncoding)
        let str2 = String(CString: UnsafePointer<CChar>(p[0].fromUserID), encoding: NSUTF8StringEncoding)
        let str4 = String(CString: UnsafePointer<CChar>(p[0].fromPlateNumber), encoding: NSUTF8StringEncoding)
         NSNotificationCenter.defaultCenter().postNotificationName("privateNotification", object: nil, userInfo: ["value1":str4!, "value2": str2!,"value3" : str!])
    }else if p[0].chat_mode == 2 {
        if p[0].trans_moder == 3 {
            //点赞
            NSNotificationCenter.defaultCenter().postNotificationName("PariseNotification", object: nil)
        }else {
            //发送消息
            let str4 = String(CString: UnsafePointer<CChar>(p[0].fromPlateNumber), encoding: NSUTF8StringEncoding)
            let str = String(CString: UnsafePointer<CChar>(p[0].testNumber), encoding: NSUTF8StringEncoding)
            NSNotificationCenter.defaultCenter().postNotificationName("gameOverNotification", object: nil, userInfo: ["value1":str4!, "value2" : str!])
        }
        
    }
   
}

class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BMKLocationServiceDelegate, IFlySpeechSynthesizerDelegate, UITextFieldDelegate {

    
    //print("---------------")
    
    //给一个存储坐标的数组
    var LocationList = [Location]()
    
    //1.定义从API中获取的数据
    var messages = [Message]()
    var tableData:[JSON]=[]
    
    //从沙盒中获取数据
    let keychain = KeychainSwift(keyPrefix: "myTestKey_")
    
    //定义发送点赞动作
    @IBAction func PariseAction(sender: AnyObject) {
        //点赞
        print("dianzan")
        let returnValue = self.send_parise()
        if returnValue == 0 {
            let numvalue = Int32(self.pariseNum.text!)!+1
            self.pariseNum.text = String(numvalue)
        }
        
    }
    
    //定义文本框和发送消息action
    @IBOutlet weak var msg_txt: UITextField!
    @IBAction func publishMsg(sender: AnyObject) {
        if msg_txt.text != "" {
            let returnValue = self.send_msg();
            
            if returnValue == 0 {
                //成功在table中增加一个list、
                let now = NSDate()
                var dateFormatter2 = NSDateFormatter()
                dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm:ss"
                
                let nowString = dateFormatter2.stringFromDate(now)
                
                self.messages.append(Message(PlatNumber: "自己", PortailUrl: "user/header/tx.png", MsgText: msg_txt.text!, TimeText: nowString))
                self.msgList!.reloadData()
                
                //隐藏键盘和文本框下拉
                UIView.animateWithDuration(0.3) { () -> Void in
                    var frame:CGRect = self.view.frame
                    frame.origin.y = 0.0
                    self.view.frame = frame
                }
                
                msg_txt.resignFirstResponder()
                msg_txt.text = nil
                
                print(returnValue)
                if returnValue == 0 {
                    //提示成功
                    self.noticeSuccess("发送成功", autoClear: true, autoClearTime: 1)
                    //滚动到最后一行
                    self.msgList.setContentOffset(CGPointMake(0, self.msgList.contentSize.height-self.msgList.bounds.size.height), animated: true)
                }
            }else {
                //发送失败
                self.errorNotice("发送失败")
            }
            

        }else {
            self.errorNotice("null!")
        }
        

    }
    
    //接收从viewController中的传递过来的信息
    var nameString: String?
    var prepString: String?
    var channelIDInt:String?//var imageName: String?
    var channelTopic:String?
    
    //定义消息列表table
    @IBOutlet weak var msgList: UITableView!
    
    //在线人数
    @IBOutlet weak var onlineNum: UILabel!
    
    //点赞个数
    @IBOutlet weak var pariseNum: UILabel!
    
    //音乐的名字
    @IBOutlet weak var MusicTitle: UILabel!
    
    //音乐的封面
    @IBOutlet weak var MusicePic: UIImageView!
    
    //播放按钮
    @IBOutlet weak var btnPlay: EkaButton!
    
    //上一首
    @IBOutlet weak var btnPre: UIButton!
    
    //下一首
    @IBOutlet weak var btnNext: UIButton!
    
    //声明一个媒体播放的实例
    var audioPlayer:MPMoviePlayerController = MPMoviePlayerController()
    
    //var eHttp:HTTPController = HTTPController()
    
    let locService = BMKLocationService()
    
    var isquit = true;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController!.tabBar.hidden = true;
        self.navigationController?.navigationBarHidden = false;
        
        //eHttp.delegate = self
        
        msgList?.dataSource = self;
        msgList?.delegate = self;
        //订阅频道
        let unsafePointerOfN1 = (channelTopic! as NSString).UTF8String
        sub_enter_channel(UnsafeMutablePointer(unsafePointerOfN1), 0)
        
        // Do any additional setup after loading the view, typically from a nib.
        self.msg_txt.delegate = self
        self.msg_txt.placeholder = "来参与互动吧"
        navigationItem.title = prepString!
        
        //获取语音列表
        let openchannelurl = "http://42.62.18.210:8090/apiradio/ar/openChannel?channelID="+channelIDInt!+"&userID="+keychain.get("QCDTSEVERUUID")!
        print(openchannelurl)
        //eHttp.onsearch(openchannelurl)
        //直接请求
        Alamofire.request(.GET, openchannelurl)
            .responseJSON { response in
                if let result = response.result.value {
                    let json = JSON(result)
                    if let messageList = json["obj"]["messageList"].array {
                        
                        //先给点赞和人数赋值
                        // print(json["obj"]["onlineCount"])
                        self.onlineNum.text = String(json["obj"]["onlineCount"])
                        self.pariseNum.text = String(json["obj"]["praiseCount"])
                        
                        self.tableData = messageList
                        for var i = 0; i < self.tableData.count; i++
                        {
                            let rowData:JSON = self.tableData[i]
                            // print(rowData["channelName"].string)
                            
                            //messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: rowData["username"].string!, MsgText: rowData["TextMsg"].string!, TimeText: rowData["audio_play_time"].string!))
                            //messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: "频道播放图片", MsgText: rowData["TextMsg"].string!, TimeText: rowData["audio_play_time"].string!))
                            self.messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: String(rowData["PortraitPath"]), MsgText: String(rowData["TextMsg"]), TimeText: self.timeStampToString(String(rowData["audio_create_time"]))))
                        }
                        
                        self.msgList!.reloadData()
                    }
                    
                }else {
                    //kongkong
                    print("kongkong")
                }
        }
        
        
        //请求音乐列表
        let misucListUrl = "http://42.62.18.210:8090/apiradio/ar/getNext?channelID="+channelIDInt!+"&userID="+keychain.get("QCDTSEVERUUID")!+"&speed=0"
        
        print(misucListUrl)
        //eHttp.onsearch(misucListUrl)
        Alamofire.request(.GET, misucListUrl)
            .responseJSON { response in
                if let result = response.result.value {
                    let json = JSON(result)
                    let MusicImageUrl = "http://imgfm.qichexiaozi.com"+String(json["obj"]["materialPicPath"]);
                    print(MusicImageUrl)
                    
                    self.MusicTitle.text = String(json["obj"]["title"])
                    
                    Alamofire.request(.GET, MusicImageUrl).response() {
                        (_, _, data, _) in
                        let image = UIImage(data: data! as NSData)
                        self.MusicePic.image = image
                    }
                    
                    //进行播放
                    let MusicPlayUrl = "http://audiofm.qichexiaozi.com/"+String(json["obj"]["materialUrl"])
                    self.onSetAudio(MusicPlayUrl)
                }
        }
        
        //为按钮绑定监听事件
        btnPlay.addTarget(self, action: "onPlay:", forControlEvents:UIControlEvents.TouchUpInside)
        btnPre.addTarget(self, action: "onClick:", forControlEvents:UIControlEvents.TouchUpInside)
        btnNext.addTarget(self, action: "onClick:", forControlEvents:UIControlEvents.TouchUpInside)
        
        //播放结束通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "playFinish", name: MPMoviePlayerPlaybackDidFinishNotification, object: audioPlayer)
        
        //在这里使用C函数的，设置相应的回调函数
        //set_sub_callback(swiftCallBackVoid)
        
        //设置消息回调的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "gameOver:", name: "gameOverNotification", object: nil)

        //设置点赞回调通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "PariseSet", name: "PariseNotification", object: nil)
        
        //设置LBS
        locService.delegate = self
        locService.desiredAccuracy = kCLLocationAccuracyBest
        locService.distanceFilter = 10
        
        locService.startUserLocationService()
        
        //创建语音合成对象等等
        var _iFlySpeechSynthesizer = IFlySpeechSynthesizer()
        _iFlySpeechSynthesizer.delegate = self
        _iFlySpeechSynthesizer.setParameter(IFlySpeechConstant.TYPE_CLOUD(), forKey: IFlySpeechConstant.ENGINE_TYPE())
        _iFlySpeechSynthesizer.setParameter("50", forKey: IFlySpeechConstant.VOLUME())
        _iFlySpeechSynthesizer.setParameter("xiaoyan", forKey: IFlySpeechConstant.VOICE_NAME())
        _iFlySpeechSynthesizer.setParameter(nil, forKey: IFlySpeechConstant.TTS_AUDIO_PATH())
        
        //发送路况请求
        dispatch_async(dispatch_get_global_queue(0, 0), {
            // something
            while(self.isquit){
                sleep(30) //过进入此界面15s后会进行请求路况信息
                if self.isquit == false {
                    break
                }else {
                
                }
                objc_sync_enter(self)
                
                //这里将数组拷贝出来，防止影响数组同时操作，导致出错
                print("--------请求路况信息---------1")
                
                let copyList = self.LocationList
                print(copyList.count)
                if copyList.count <= 0 {
                    continue;
                }
                
                let returnValue = self.GetTraffic(copyList)
                
                print("--------请求路况信息---------2")
                print(returnValue)
                
                //http://42.62.18.210:8090/apiradio/ar/getTraffic?lng=Optional(116.313966702337)&lat=Optional(39.9900268934891)&license=38441073780e49e4879586419cd65311&location=SwAxMjM0NTY3OAAHbs/uBhIzYgK/b3pW////8f/8/wD///8PAAAAAP///wAA/P8A////AAAAAAD///8AAAAAAP///wAAAAAA////DQo=
                //在这里进行请求路况信息
                let test1 = copyList.last?.longitude
                let test2 = copyList.last?.latitude
            
                
                var urladdress:String?
                if self.keychain.get("registerUserID") != nil {
                     urladdress = "http://42.62.18.210:8090/apiradio/ar/getTraffic?lng="+String(test1!)+"&lat="+String(test2!)+"&license="+self.keychain.get("QCDTTRAFFICID")!+"&location="+returnValue+"&location_type=1&userSign="+self.keychain.get("registerUserID")!
                }else {
                    urladdress = "http://42.62.18.210:8090/apiradio/ar/getTraffic?lng="+String(test1!)+"&lat="+String(test2!)+"&license="+self.keychain.get("QCDTTRAFFICID")!+"&location="+returnValue+"&location_type=1&userSign="+self.keychain.get("QCDTSEVERUUID")!
                }

                print(urladdress)
                Alamofire.request(.GET, urladdress!)
                    .responseJSON { response in
                        if let result = response.result.value {
                            print("JSON: \(result)")
                            //self.audioPlayer.pause()
                            //_iFlySpeechSynthesizer.startSpeaking("床前明月光,疑是地上霜")
                            let json = JSON(result)
                            if json["obj"]["traffic"] {
                                self.audioPlayer.pause()
                                _iFlySpeechSynthesizer.startSpeaking(String(json["obj"]["traffic"]))

                            }else {
                                
                            }
                            
                        }
                }
                
                objc_sync_exit(self)
            }
        });
        
        //invokeCallBackVoid(swiftCallBackVoid)
    }
    
    func PariseSet() {
        //增加pariseNum
        print("+++++1")
        dispatch_async(dispatch_get_main_queue(),{
            let numvalue = Int32(self.pariseNum.text!)!+1
            self.pariseNum.text = String(numvalue)
        })
        
    }
    
    //函数
    func gameOver(notification:NSNotification)
    {
        let userInfo = notification.userInfo as! [String: AnyObject]
        let value1 = userInfo["value1"] as! String
        let value2 = userInfo["value2"] as! String
        
        print(value1)
        print(value2)
        

        //成功在table中增加一个list
        let now = NSDate()
        var dateFormatter2 = NSDateFormatter()
        dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let nowString = dateFormatter2.stringFromDate(now)
        self.messages.append(Message(PlatNumber: value1, PortailUrl: "user/header/tx.png", MsgText: value2, TimeText: nowString))
        
        dispatch_async(dispatch_get_main_queue(),{
            self.msgList?.reloadData()
            
            //滚动到最后一行
            self.msgList.setContentOffset(CGPointMake(0, self.msgList.contentSize.height-self.msgList.bounds.size.height), animated: true)
        })
        
    
        
    }
    
    //在即将输入文本时，将文本框弹出
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("begin edit")
        
        var offset:CGFloat = self.view.frame.size.height - (msg_txt.frame.origin.y + msg_txt.frame.size.height + 216 + 50)
        
        if offset <= 0 {
            UIView.animateWithDuration(0.3, animations: { () -> Void in
                var frame:CGRect = self.view.frame
                frame.origin.y = offset
                self.view.frame = frame
            })
        }
        
        return true
    }
    
    //重新恢复文本框
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        UIView.animateWithDuration(0.3) { () -> Void in
            var frame:CGRect = self.view.frame
            frame.origin.y = 0.0
            self.view.frame = frame
        }
        
        msg_txt.resignFirstResponder()
        return true
    }
    
    

    
    //重新恢复文本框
    
    func playFinish() {
        print("------***----------")
        
        
        //请求下一首歌曲
        let NextMusicUrl = "http://42.62.18.210:8090/apiradio/ar/getNext?channelID="+self.channelIDInt!+"&userID="+keychain.get("QCDTSEVERUUID")!+"&speed=0"
        print(NextMusicUrl)
        Alamofire.request(.GET, NextMusicUrl)
            .responseJSON { response in
                
                if let result = response.result.value {
                    print("JSON: \(result)")
                    let json = JSON(result)
                    
                    //先对背景封面进行设置
                    let MusicImageUrl = "http://imgfm.qichexiaozi.com"+String(json["obj"]["materialPicPath"]);
                    print(MusicImageUrl)
                    
                    self.MusicTitle.text = String(json["obj"]["title"])
                    
                    Alamofire.request(.GET, MusicImageUrl).response() {
                        (_, _, data, _) in
                        let image = UIImage(data: data! as NSData)
                        self.MusicePic.image = image
                    }
                    
                    
                    //播放下一首
                    let MusicUrl = "http://audiofm.qichexiaozi.com/"+String(json["obj"]["materialUrl"])
                    
                    print(MusicUrl)
                    //self.onSetAudio(MusicUrl)
                    self.audioPlayer.contentURL = NSURL(string: MusicUrl)
                    self.audioPlayer.play()
                    /*
                    dispatch_async(dispatch_get_main_queue(),{
                            self.audioPlayer.play()
                    })*/
                }
        }
    }
    
    
    //初始化一下语音合成参数
    
    
    //代理实现
    func onCompleted(error: IFlySpeechError!) {
        self.audioPlayer.play()
    }
    
    func onSpeakBegin() {
        
    }
    
    func onBufferProgress(progress: Int32, message msg: String!) {
        
    }
    
    func onSpeakProgress(progress: Int32) {
        
    }
    
    //编码坐标
    func GetTraffic(allLocation: [Location])->String {
        var testSwift2oc = TestSwift2OC()
        print("wo log 1111")
        //testSwift2oc.SetTime()
        testSwift2oc.SetProbe(self.keychain.get("QCDTTRAFFICID")!)
        print("wo log 2222")
        
        print(allLocation.count)
        //testSwift2oc.TestOCStr(allLocation)
        if(allLocation.count <= 7) {
            //调用相应的函数
            var j = 0;
            print("wo log 3333")
            
            for var i=0; i<7; i++ {
                if(i > allLocation.count-1) {
                    j = allLocation.count-1
                }else {
                    j = i
                }
                print("wo log 4444")
                testSwift2oc.AddXY(allLocation[j].longitude, para2: allLocation[j].latitude, para3: allLocation[j].speed, para4: allLocation[j].direct, para5: (Int32)(i*2), para6: allLocation[j].time)
            }
            
        }else {
        
        }
        
        let tempStr:String = testSwift2oc.EncodeBase64()
        testSwift2oc.clearAll()

        return tempStr
    }
    
    
    //当坐标改变时,调用该函数
    func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) {
        print("--------------")
        objc_sync_enter(self)
        print("\(userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude)")
        
        //在这里需将坐标加入List中
        print(Int32(NSDate().timeIntervalSince1970))
        
        LocationList.append(Location(latitude: userLocation.location.coordinate.latitude, longitude: userLocation.location.coordinate.longitude, speed: userLocation.location.speed, direct: userLocation.location.course, time: Int32(NSDate().timeIntervalSince1970)))
        
        if(LocationList.count > 7) {
            //退
            LocationList.removeFirst()
            
        }else {
            //获取时间戳
            
        }
        objc_sync_exit(self)
         /*
        var test:CLLocationCoordinate2D = CLLocationCoordinate2D()
        test.latitude   = userLocation.location.coordinate.latitude
        test.longitude  = userLocation.location.coordinate.longitude
        
       
        let test2:CLLocationCoordinate2D = transformFromWGSToGCJ(test)

        
        print("After Change:\(test.latitude)")
        print("After Change:\(test.longitude)")
        */
    }
    
    func onClick(btn:UIButton) {
        //请求下一首歌曲
        let NextMusicUrl = "http://42.62.18.210:8090/apiradio/ar/getNext?channelID="+self.channelIDInt!+"&userID="+keychain.get("QCDTSEVERUUID")!+"&speed=0"
        print(NextMusicUrl)
        Alamofire.request(.GET, NextMusicUrl)
            .responseJSON { response in
                
                if let result = response.result.value {
                    print("JSON: \(result)")
                    let json = JSON(result)
                    
                    //先对背景封面进行设置
                    let MusicImageUrl = "http://imgfm.qichexiaozi.com"+String(json["obj"]["materialPicPath"]);
                    print(MusicImageUrl)
                    
                    self.MusicTitle.text = String(json["obj"]["title"])
                    
                    Alamofire.request(.GET, MusicImageUrl).response() {
                        (_, _, data, _) in
                        let image = UIImage(data: data! as NSData)
                        self.MusicePic.image = image
                    }
                    
                    
                    //播放下一首
                    let MusicUrl = "http://audiofm.qichexiaozi.com/"+String(json["obj"]["materialUrl"])
                    
                    //self.onSetAudio(MusicUrl)
                    //self.audioPlayer.pause()
                    self.audioPlayer.contentURL = NSURL(string: MusicUrl)
                    
                    self.audioPlayer.play()
                    
                    self.btnPlay.onPlay()
                }
        }
    }
    
    func onPlay(btn:EkaButton) {
        if btn.isPlay {
            audioPlayer.play()
        }else {
            audioPlayer.pause()
        }
    }
    
    // MARK: - UITableView DataSource Methods
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier: String = "msgCell"
        
        var cell: MsgList! = tableView.dequeueReusableCellWithIdentifier(identifier) as? MsgList
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        if cell == nil {
            cell = MsgList(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
        }
        
        cell.configurateTheCell(messages[indexPath.row])
        //configurateTheCell();
        
        return cell!
    }
    
    func configurateTheCell()->Int {
        //配置table里面的值
        return 0;
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }
    
    //时间戳转换
    func timeStampToString(timeStamp:String)->String {
        var ns2=(timeStamp as NSString).substringToIndex(10)
        
        var string = NSString(string: ns2)
        
        var timeSta:NSTimeInterval = string.doubleValue
        var dfmatter = NSDateFormatter()
        dfmatter.dateFormat="yyyy年MM月dd日"
        
        var date = NSDate(timeIntervalSince1970: timeSta)
        
        print(dfmatter.stringFromDate(date))
        return dfmatter.stringFromDate(date)
    }
    
    /* 获取数据的回调函数 */
    func didRecieveResults(results: AnyObject) {
        
        let json = JSON(results)
        print(json)
        if let messageList = json["obj"]["messageList"].array {
            
            //先给点赞和人数赋值
            // print(json["obj"]["onlineCount"])
            self.onlineNum.text = String(json["obj"]["onlineCount"])
            self.pariseNum.text = String(json["obj"]["praiseCount"])
            
            tableData = messageList
            for var i = 0; i < tableData.count; i++
            {
                let rowData:JSON = tableData[i]
                // print(rowData["channelName"].string)
                
                //messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: rowData["username"].string!, MsgText: rowData["TextMsg"].string!, TimeText: rowData["audio_play_time"].string!))
                //messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: "频道播放图片", MsgText: rowData["TextMsg"].string!, TimeText: rowData["audio_play_time"].string!))
                messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: String(rowData["PortraitPath"]), MsgText: String(rowData["TextMsg"]), TimeText: timeStampToString(String(rowData["audio_create_time"]))))
            }
            
            self.msgList!.reloadData()
        }else {
            //对图片封面,音乐名字等进行赋值
            let MusicImageUrl = "http://imgfm.qichexiaozi.com"+String(json["obj"]["materialPicPath"]);
            print(MusicImageUrl)
            
            self.MusicTitle.text = String(json["obj"]["title"])
            
            Alamofire.request(.GET, MusicImageUrl).response() {
                (_, _, data, _) in
                let image = UIImage(data: data! as NSData)
                self.MusicePic.image = image
            }
            
            //进行播放
            let MusicPlayUrl = "http://audiofm.qichexiaozi.com/"+String(json["obj"]["materialUrl"])
            self.onSetAudio(MusicPlayUrl)
            
            //NSNotificationCenter.defaultCenter().addObserver(self, selector: "playFinish", name: MPMoviePlayerPlaybackDidFinishNotification, object: audioPlayer)
            
        }
        
        /*
        //print("results: \(results)")
        let json = JSON(results)
        print(json)
        
        
        if let messageList = json["obj"]["messageList"].array {
            
            //先给点赞和人数赋值
            // print(json["obj"]["onlineCount"])
            self.onlineNum.text = String(json["obj"]["onlineCount"])
            self.pariseNum.text = String(json["obj"]["praiseCount"])
            
            
            //给语音列表进行赋值
            tableData = messageList
            //print(tableData.count)
            
            
            for var i = 0; i < tableData.count; i++
            {
                let rowData:JSON = tableData[i]
                // print(rowData["channelName"].string)
                
                //messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: rowData["username"].string!, MsgText: rowData["TextMsg"].string!, TimeText: rowData["audio_play_time"].string!))
                messages.append(Message(PlatNumber: String(rowData["username"]), PortailUrl: "频道播放图片", MsgText: rowData["TextMsg"].string!, TimeText: rowData["audio_play_time"].string!))
            }
            
            self.msgList!.reloadData()
        }else {
            //对图片封面,音乐名字等进行赋值
            let MusicImageUrl = "http://testimg.qichexiaozi.com"+String(json["obj"]["materialPicPath"]);
            print(MusicImageUrl)
            
            self.MusicTitle.text = String(json["obj"]["title"])
            
            Alamofire.request(.GET, MusicImageUrl).response() {
                (_, _, data, _) in
                let image = UIImage(data: data! as NSData)
                self.MusicePic.image = image
            }
            
            //进行播放
            let MusicPlayUrl = "http://audio.qichexiaozi.com/"+String(json["obj"]["materialUrl"])
            self.onSetAudio(MusicPlayUrl)
            
        }*/
    }
    
    
    override func viewWillDisappear(animated: Bool) {
        //print("quit2")
        let unsafePointerOfN1 = (channelTopic! as NSString).UTF8String
        sub_quit_channel(UnsafeMutablePointer(unsafePointerOfN1))
        self.tabBarController!.tabBar.hidden = false;
        
        //退出线程
        self.isquit = false;
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackDidFinishNotification, object: audioPlayer)
        
    }
    
    override func didReceiveMemoryWarning() {
        print("quit")
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //发送消息(目前只支持消息)
    func send_parise()->Int32 {
        //在这里就可以写pub函数
        //test1--发送消息
        var pub_object = carRadio_pub()
        
        
        var userUUID:String?
        if keychain.get("registerUserID") != nil {
            userUUID =  keychain.get("registerUserID")
            pub_object.user_type = 1;
            let username = self.keychain.get("QCDTUSERNAME")
            let unsafePointerOfN12 = (username! as NSString).UTF8String
            pub_object.user_name = UnsafeMutablePointer(unsafePointerOfN12)
        }else {
            userUUID =  keychain.get("QCDTSEVERUUID")
            pub_object.user_type = 0;
            let unsafePointerOfN12 = ("匿名" as NSString).UTF8String
            pub_object.user_name = UnsafeMutablePointer(unsafePointerOfN12)
        }
        
        let unsafePointerOfN1 = (userUUID! as NSString).UTF8String
        pub_object.uuid = UnsafeMutablePointer(unsafePointerOfN1)
        
        let unsafePointerOfN2 = (channelIDInt! as NSString).UTF8String
        pub_object.channel_id = UnsafeMutablePointer(unsafePointerOfN2)
        
        
        pub_object.client_type = 1;
        pub_object.quiet = false;
        pub_object.retain = false;
        
        let unsafePointerOfN3 = ("/home" as NSString).UTF8String
        pub_object.portrait_path = UnsafeMutablePointer(unsafePointerOfN3)
        
        let unsafePointerOfN4 = ("/storage/emulated/0/1.txt" as NSString).UTF8String
        pub_object.file_path = UnsafeMutablePointer(unsafePointerOfN4)
        
        let unsafePointerOfN5 = (msg_txt.text! as NSString).UTF8String
        pub_object.message = UnsafeMutablePointer(unsafePointerOfN5)
        
        let unsafePointerOfN6 = (channelTopic! as NSString).UTF8String
        pub_object.topic = UnsafeMutablePointer(unsafePointerOfN6)
        
        let unsafePointerOfN7 = ("123.56.93.31" as NSString).UTF8String
        pub_object.server_ip = UnsafeMutablePointer(unsafePointerOfN7)
        
        pub_object.server_port = 1883;                  // 服务器端口号
        
        pub_object.sender_type = 2;            //资源类型: 1-Java调用C; 2-用户发送; 3-运营发送; 4-机器人发送
        pub_object.trans_mode = 3;          // 传输信息类型: 1.语音 2.消息 3.点赞命令 4.上线命令 5.下线命令
        pub_object.file_type = 1;        // 文件类型:音频(mp3、amr等等)
        pub_object.audio_play_time = 3;   // 语音发送时长，如果不是语音则为0
        
        pub_object.chat_mode = 2;
        
        let unsafePointerOfN8 = ("123456" as NSString).UTF8String
        pub_object.toUserID = UnsafeMutablePointer(unsafePointerOfN8)
        
        pub_object.product_type = 1;         // 产品类型
        
        let unsafePointerOfN9 = ("kx" as NSString).UTF8String
        pub_object.product_id = UnsafeMutablePointer(unsafePointerOfN9)
        
        let unsafePointerOfN10 = ("苹果" as NSString).UTF8String
        pub_object.brand = UnsafeMutablePointer(unsafePointerOfN10)
        
        let unsafePointerOfN11 = ("iPhone9.1" as NSString).UTF8String
        pub_object.phone_type = UnsafeMutablePointer(unsafePointerOfN11)
        
        
        let returnValue = pub_send_msg(pub_object)
        
        print(returnValue)
        return returnValue;
    }
    
    
    //发送消息(目前只支持消息)
    func send_msg()->Int32 {
        //在这里就可以写pub函数
        //test1--发送消息
        var pub_object = carRadio_pub()
        
        
        var userUUID:String?
        if keychain.get("registerUserID") != nil {
            userUUID =  keychain.get("registerUserID")
            pub_object.user_type = 1;
            let username = self.keychain.get("QCDTUSERNAME")
            let unsafePointerOfN12 = (username! as NSString).UTF8String
            pub_object.user_name = UnsafeMutablePointer(unsafePointerOfN12)
        }else {
            userUUID =  keychain.get("QCDTSEVERUUID")
             pub_object.user_type = 0;
            let unsafePointerOfN12 = ("匿名" as NSString).UTF8String
            pub_object.user_name = UnsafeMutablePointer(unsafePointerOfN12)
        }
        
        let unsafePointerOfN1 = (userUUID! as NSString).UTF8String
        pub_object.uuid = UnsafeMutablePointer(unsafePointerOfN1)
        
        let unsafePointerOfN2 = (channelIDInt! as NSString).UTF8String
        pub_object.channel_id = UnsafeMutablePointer(unsafePointerOfN2)
        
       
        pub_object.client_type = 1;
        pub_object.quiet = false;
        pub_object.retain = false;
        
        let unsafePointerOfN3 = ("/home" as NSString).UTF8String
        pub_object.portrait_path = UnsafeMutablePointer(unsafePointerOfN3)
        
        let unsafePointerOfN4 = ("/storage/emulated/0/1.txt" as NSString).UTF8String
        pub_object.file_path = UnsafeMutablePointer(unsafePointerOfN4)
        
        let unsafePointerOfN5 = (msg_txt.text! as NSString).UTF8String
        pub_object.message = UnsafeMutablePointer(unsafePointerOfN5)
        
        let unsafePointerOfN6 = (channelTopic! as NSString).UTF8String
        pub_object.topic = UnsafeMutablePointer(unsafePointerOfN6)
        
        let unsafePointerOfN7 = ("123.56.93.31" as NSString).UTF8String
        pub_object.server_ip = UnsafeMutablePointer(unsafePointerOfN7)
        
        pub_object.server_port = 1883;                  // 服务器端口号
        
        pub_object.sender_type = 1;            //资源类型: 1-Java调用C; 2-用户发送; 3-运营发送; 4-机器人发送
        pub_object.trans_mode = 2;          // 传输信息类型: 1.语音 2.消息 3.点赞命令 4.上线命令 5.下线命令
        pub_object.file_type = 1;        // 文件类型:音频(mp3、amr等等)
        pub_object.audio_play_time = 3;   // 语音发送时长，如果不是语音则为0
        
        pub_object.chat_mode = 2;
        
        let unsafePointerOfN8 = ("123456" as NSString).UTF8String
        pub_object.toUserID = UnsafeMutablePointer(unsafePointerOfN8)
        
        pub_object.product_type = 1;         // 产品类型
        
        let unsafePointerOfN9 = ("kx" as NSString).UTF8String
        pub_object.product_id = UnsafeMutablePointer(unsafePointerOfN9)
        
        let unsafePointerOfN10 = ("苹果" as NSString).UTF8String
        pub_object.brand = UnsafeMutablePointer(unsafePointerOfN10)
        
        let unsafePointerOfN11 = ("iPhone9.1" as NSString).UTF8String
        pub_object.phone_type = UnsafeMutablePointer(unsafePointerOfN11)
        
        
        let returnValue = pub_send_msg(pub_object)
        
        print(returnValue)
        return returnValue;
    }
    
    //播放音乐
    func onSetAudio(url:String) {
        print("Start Play"+url)
        self.audioPlayer.pause()
        self.audioPlayer.contentURL = NSURL(string: url)
        
        self.audioPlayer.play()
        
        btnPlay.onPlay()
    }
    
    //判断此坐标是否在中国
    func isLocationOutOfChina(location:CLLocationCoordinate2D)->Bool {
        if(location.longitude < 72.004 || location.longitude > 137.8347 || location.latitude < 0.8293 || location.latitude > 55.8271) {
            return true
        }else {
            return false
        }
    }
    

    //转换函数
    func transformLatWithX(x:Double, y:Double) ->Double{
        let pi:Double = 3.14159265358979324;
        let changex:Double = sqrt(fabs(x))
        var lat:Double = -100.0 + 2.0*x + 3.0*y + 0.2*y*y + 0.1*x*y + 0.2*changex
        
        
        lat += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
        lat += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0;
        lat += (160.0 * sin(y / 12.0 * pi) + 320 * sin(y * pi / 30.0)) * 2.0 / 3.0;
        
        return lat
    }
    
    func transformLonWithX(x:Double, y:Double) ->Double{
    
        let pi:Double = 3.14159265358979324;
        let changex:Double = sqrt(fabs(x))
        var lon:Double = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1*changex;
        lon += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
        lon += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0;
        lon += (150.0 * sin(x / 12.0 * pi) + 300.0 * sin(x / 30.0 * pi)) * 2.0 / 3.0;
        return lon
    }
    
    //对坐标进行转换
    func transformFromWGSToGCJ(wgsLoc:CLLocationCoordinate2D)-> CLLocationCoordinate2D{
        let pi:Double = 3.14159265358979324;
        let ee:Double = 0.00669342162296594323;
        let a:Double  = 6378245.0;
        var adjustLoc:CLLocationCoordinate2D = CLLocationCoordinate2D()
        if(self.isLocationOutOfChina(wgsLoc)) {
            adjustLoc = wgsLoc
        }else {
            print("zhuanhuan")
            var adjustLat:Double = self.transformLatWithX(wgsLoc.longitude - 105.0, y:wgsLoc.latitude - 35.0)
            var adjustLon:Double = self.transformLonWithX(wgsLoc.longitude - 105.0, y:wgsLoc.latitude - 35.0)
            
            let radLat:Double = wgsLoc.latitude / 180.0 * pi;
            var magic:Double  = sin(radLat);
            magic = 1 - ee * magic * magic;
            let sqrtMagic:Double = sqrt(magic);
            adjustLat = (adjustLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
            adjustLon = (adjustLon * 180.0) / (a / sqrtMagic * cos(radLat) * pi);
            adjustLoc.latitude = wgsLoc.latitude + adjustLat;
            adjustLoc.longitude = wgsLoc.longitude + adjustLon;
        }
        
        return adjustLoc
    }
    
}